package net.wesley.android.city;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

import android.os.Handler;
import android.os.Message;
import android.util.Log;

import net.wesley.android.City;
import net.yebaihe.sdk.HttpConnection;

public class GuangZhou extends City {

	private Handler requesthandler=new Handler(){
		public void handleMessage(Message message){
			boolean firstrow;
			String retvalue;
			switch (message.what){
			case HttpConnection.DID_ERROR://DID ERROR
				callback.onComplete(-1, "");
				break;
			case HttpConnection.DID_SUCCEED://DID SUCC
				String str=(String)message.obj;
		        if (str.indexOf("是否确认")<=0){
		        	callback.onComplete(0, "");
		            return;
		        }
		        
		        if (str.indexOf(chepai+"  02")>0){
		        	String error=str.split(chepai+"  02")[1].split("</td>")[0].trim();
		        	if (error.length()>1){
		        		callback.onComplete(-10001, "ret:"+error.substring(1).trim());
		        		return;
		        	}
		        }
		        
		        str=str.split("是否确认")[1];
		        str=str.split("</table>")[0];
		        String[] rows=str.split("<tr");
		        firstrow=true;
		        retvalue="";
		        for (int i=0;i<rows.length;i++){
		            if (firstrow){
		                firstrow=false;
		                continue;
		            }
		            String row=rows[i];
		            String[] cols = row.split("<td");
		            Log.d("myown", "cols:"+cols.toString());
		            String shijian = cols[3].split(">")[1].split("<")[0];
		            String didian = cols[4].split(">")[1].split("<")[0];
		            String code = cols[6].split(">")[1].split("<")[0];
		            retvalue+=String.format("shijian:%s\ndidian:%s\ncode:%s\n\n",shijian,didian,code);
		        }
		        callback.onComplete(rows.length-1, retvalue);
				break;
			}
		}
	};

	public void requestParamsFinish(String[] values) {
		try {
			new HttpConnection(ctx,requesthandler,"GBK").post("http://www.gzjd.gov.cn/gzwfcx/chaxunservlet?ywlx=cxlist", 
					String.format("hpzl=02&hphm=%s&fdjh=%s&yzm=IJVX&jm=156756dfgd75sdfsdf123fasdfsdfsdf%s%s&mode=2&hphm2=%s&move=&sjc=%s&url=/gzwfcx",
							chepai.substring(1),values[0],chepai.substring(1),values[0],URLEncoder.encode(chepai,"GBK"),URLEncoder.encode("粤","GBK")));
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
	}

	@Override
	public boolean match(String chepai) {
		return chepai.startsWith("粤A");
	}

	@Override
	public String[] paramDesc() {
		String[] s={"发动机号后四位"};
		return s;
	}

}
